/*
    Bandleader
    Copyright (c) 2006 by Grant Yoshida

    Licensed under the GPL version 2 or later,
    please see COPYING for details.
*/

#include "MidiPlayer.h"
//
#include "improv/MidiPerform.h"
//
#include <QtCore/QString>
#include <QtCore/QTimer>

MidiPlayer::MidiPlayer(QObject *parent) :
    QObject(parent),
    m_performance(),
    m_playing(false),
    m_playTimer(new QTimer(this))
{
    m_playTimer->setInterval(1);
    m_playTimer->setSingleShot(false);
    connect(m_playTimer, SIGNAL(timeout()),
            this, SLOT(timerTick()));
}

void MidiPlayer::load(const QString &fileName)
{
    if (!m_performance) {
        m_performance.reset(new MidiPerform());
        m_performance->setPort(0);
        m_performance->open();

        m_performance->channelCollapse(0);
    }

    m_performance->read(fileName.toStdString().c_str());
}

void MidiPlayer::play()
{
    if (m_playing)
        return;

    m_playing = true;

    m_performance->setTempo(120);
    m_performance->setTempoMethod(TEMPO_METHOD_AUTOMATIC);

    m_playTimer->start();
}

void MidiPlayer::timerTick()
{
    if (m_performance) {
        if (!m_performance->check())
            stop();
    }
}

void MidiPlayer::pause()
{
    stop();
}

void MidiPlayer::stop()
{
    if (!m_playing)
        return;

    m_playing = false;

    m_playTimer->stop();

    if (m_performance) {
        m_performance->stop();
        m_performance->silence();
    }

    stopped();
}


bool MidiPlayer::isPlaying() const
{
    return m_playing;
}


int MidiPlayer::beatCount() const
{
    return m_performance ? m_performance->getBeatLocation() : 0;
}

QTimer *MidiPlayer::playTimer() const
{
    return m_playTimer;
}
